package com.adqua.testfacebook;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;

public class LoginActivity extends Activity {
	
	Button infoBtn;
	Button facebookBtn;
	AlertDialog exit_alert;
	private ProgressDialog loadingdialog;

	  @Override
	  public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_login);
	    
	    loadingdialog = new ProgressDialog( this );

	    loadingdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	    loadingdialog.setMessage("please wait....");
	    
	    infoBtn = (Button) findViewById(R.id.button1);
	    facebookBtn = (Button) findViewById(R.id.authButton);
	    
	    infoBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				Intent infoIntent = new Intent(LoginActivity.this, InfoActivity.class);
				
				startActivity(infoIntent);
								
			}
		});
	    
	    facebookBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				faceLogin();
			}
		});
	    
	  }
	  
	  public void faceLogin(){
		  
		    // start Facebook Login
		    Session.openActiveSession(this, true, new Session.StatusCallback() {
		    	 
		      // callback when session changes state
		      @Override
		      public void call(Session session, SessionState state, Exception exception) {
		    	  
		    	  if (session.isOpened()) {
		    		  
		    		  loadingdialog.show();
		        	
		          // make request to the /me API
		          Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
		        	  
		            // callback after Graph API response with user object
		            @Override
		            public void onCompleted(GraphUser user, Response response) {
		            	 
		              if (user != null) {
		          
		            	  new getLoginInfo().execute(user.getId());
		            	  
		            	  /*Intent intent = new Intent(LoginActivity.this, StampActivity.class);
		            	  intent.putExtra("name", user.getName());
		            	  intent.putExtra("id", user.getId());
			          	  startActivity(intent);
		            	  
			          	  Toast.makeText(LoginActivity.this, "로그인이 완료되었습니다.", Toast.LENGTH_SHORT).show();*/
		            	  
		              }
		            }
		          });
		        }
		      }
		    });
		    }

	  @Override
	  public void onActivityResult(int requestCode, int resultCode, Intent data) {
	      super.onActivityResult(requestCode, resultCode, data);
	      Session.getActiveSession().onActivityResult(LoginActivity.this, requestCode, resultCode, data);
	      
	      	if (resultCode == RESULT_OK) {
	      		
	      		Session.openActiveSession(this, true, new Session.StatusCallback() {
	   	    	 
	      	      @Override
	      	      public void call(Session session, SessionState state, Exception exception) {
	      	    	loadingdialog.show();
	      	        if (session.isOpened()) {
	      	        	
	      	          Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
	      	        	  
	      	            @Override
	      	            public void onCompleted(GraphUser user, Response response) {
	      	            	 
	      	              if (user != null) {
	      	            	 
	      	            	Intent intent = new Intent(LoginActivity.this, ConfirmActivity.class);
	      	            	intent.putExtra("name", user.getName());
	      	            	intent.putExtra("id", user.getId());
	      		          	startActivity(intent);
	      		          	  
	      		          	Toast.makeText(LoginActivity.this, "로그인이 완료되었습니다.", Toast.LENGTH_SHORT).show();
	      	            	  
	      	              }
	      	            }
	      	          });
	      	        }
	      	      }
	      	    });
	      	}
	  }
	  
	  class getLoginInfo extends AsyncTask<String, String, String> {
			
			@Override
			protected void onPostExecute(String result) {
			
				super.onPostExecute(result);
				
				try {

    				JSONObject jsonObject = new JSONObject(result);

    				String idChk = jsonObject.getString("idChk").toString();
    				String userId = jsonObject.getString("userId").toString();
    				String userName = jsonObject.getString("userName").toString();

    				if (idChk.equals("Y")) {
    					
    					Intent intent = new Intent(LoginActivity.this, StampActivity.class);
    					intent.putExtra("name", userName);
    					intent.putExtra("id", userId);
		          	  	startActivity(intent);
		          	  Toast.makeText(LoginActivity.this, "로그인이 완료되었습니다.", Toast.LENGTH_SHORT).show();
		          	  	
    				} else {
    					Intent intent = new Intent(LoginActivity.this, ConfirmActivity.class);
    					intent.putExtra("name", userName);
    					intent.putExtra("id", userId);
		          	  	startActivity(intent);
    				}

    			} catch (JSONException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
				
			}

			@Override
			protected void onPreExecute() {

			}

			@Override
			protected void onProgressUpdate(String... values) {
				super.onProgressUpdate(values);
			}

			@Override
			protected void onCancelled() {
				super.onCancelled();
			}

			@Override
			protected String doInBackground(String... params) {
				
			  InputStream is = null;
          	  String result = null;
          	  String userId = params.toString();
          	  String url = "http://www3.bohae.co.kr/test_login.php?userId="+ userId;
          	
				try {
					DefaultHttpClient httpclient = new DefaultHttpClient();
					HttpGet httpget = new HttpGet(url);
					HttpParams paramss = httpclient.getParams();
					HttpConnectionParams.setConnectionTimeout(paramss, 5000);
					HttpConnectionParams.setSoTimeout(paramss, 5000);
					HttpResponse response = httpclient.execute(httpget);
					HttpEntity entityResponse = response.getEntity();
					is = entityResponse.getContent();
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "utf-8"), 8);

					StringBuilder sb = new StringBuilder();
					String line = null;
					while ((line = reader.readLine()) != null) {
						sb.append(line).append("\n");
					}
					is.close();
					result = sb.toString();

				} catch (IOException e) {
					e.toString();
				}
				return result;

			}
		}
	  
	  @Override
		public void onBackPressed() {
			exit_alert = new AlertDialog.Builder(this).setTitle("").setMessage(
					"종료하시겠습니까?").setPositiveButton("ok",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							moveTaskToBack(true);
							finish();
							android.os.Process.killProcess(android.os.Process.myPid());
						}
					}).setNegativeButton("cancel", null).show();
		}
	  

	}